package com.jike.master.select;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyReadWriteLock {
	
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	private Lock readLock = lock.readLock();
	
	private Lock writeLock = lock.writeLock();
	
	public void get() {
		try {
			readLock.lock();
			System.out.println("开始读");
			Thread.sleep(10000);
			System.out.println("读完");
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			readLock.unlock();
		}
	}
	
	public void write() {
		try {
			writeLock.lock();
			System.out.println("开始写");
			System.out.println("写完");
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			writeLock.unlock();
		}
	}
	
}


public class TestReadWriteLock {
	
	public static void main(String[] args) throws Exception {
		final MyReadWriteLock lock = new MyReadWriteLock();
		Thread t1 = new Thread(
				new Runnable() {
					
					public void run() {
						// TODO Auto-generated method stub
						lock.get();
					}
				}
				);
		t1.start();
		
		Thread.sleep(100);
		
		Thread t2 = new Thread(
				new Runnable() {
					
					public void run() {
						// TODO Auto-generated method stub
						lock.write();
					}
				}
				);
		
		t2.start();
	}

}
